package com.hy.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hy.common.Result;
import com.hy.dto.collection.UserCollectionDTO;
import com.hy.dto.user.UserDTO;
import com.hy.entity.User;
import com.hy.entity.UserCollection;
import com.hy.entity.vo.GenderStatisticsVO;
import com.hy.entity.vo.UserVO;
import com.hy.exception.BusinessException;
import com.hy.service.UserCollectionService;
import com.hy.service.UserService;
import com.hy.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/userCollections")
public class UserCollectionController {

    @Autowired
    private UserCollectionService userCollectionService;

    @Autowired
    private UserUtil userUtil;
    @Autowired
    private UserService userService;

    @GetMapping("/userList")
    public Result getUserList() {
        List<User> allUsers = userService.getAllUsers();
        return Result.success(allUsers);
    }
    /**
     * 获取用户的所有收藏
     */
    @GetMapping("/user")
    public Result<List<UserCollectionDTO>> getUserCollections() {
        Integer userId = userUtil.getUserIdFromToken();
        return Result.success(userCollectionService.getUserCollections(userId.longValue()));
    }

    /**
     * 获取指定用户的所有收藏
     */
    @GetMapping("/user/{userId}")
    public Result<List<UserCollectionDTO>> getUserCollections(@PathVariable Long userId) {
        return Result.success(userCollectionService.getUserCollections(userId));
    }

    /**
     * 添加收藏
     */
    @PostMapping
    public Result<Void> addCollection(@RequestBody UserCollection userCollection) {
        return userCollectionService.addCollection(userCollection);
    }

    /**
     * 取消收藏
     */
    @PutMapping("/cancel/{id}")
    public Result<Boolean> cancelCollection(@PathVariable Long id) {
        return Result.success(userCollectionService.cancelCollection(id));
    }

    /**
     * 检查是否已收藏
     */
    @GetMapping("/check")
    public Result<Boolean> isCollected(@RequestParam Long userId, @RequestParam Long collectionId) {
        return Result.success(userCollectionService.isCollected(userId, collectionId));
    }
    @GetMapping("/admin/template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        userService.exportMemberTemplate(response);
    }
    // 导入 Excel
    @PostMapping("/admin/import")
    public Result importMembers(@RequestParam("file") MultipartFile file) {
        try {
            userService.importMembers(file);
            return Result.success();
        } catch (BusinessException e) {
            return Result.error( e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(500, "系统异常，请联系管理员");
        }
    }

    // 新增会员
    @PostMapping("/admin/add")
    public Result addMember(@RequestBody @Valid UserDTO userDTO) {
        userService.addMember(userDTO);
        return Result.success();
    }

    // 删除会员
    @DeleteMapping("/admin/{id}")
    public Result deleteMember(@PathVariable Integer id) {
        userService.deleteMember(id);
        return Result.success();
    }

    // 更新会员
    @PutMapping("/admin/update")
    public Result updateMember(@RequestBody @Valid UserDTO userDTO) {
        System.out.println("userDTO = " + userDTO);
        if (userDTO.getId() == null) {
            return Result.error(400, "ID不能为空");
        }
        userService.updateMember(userDTO);
        return Result.success();
    }

    // 根据 ID 查询会员
    @GetMapping("/admin/{id}")
    public Result getMember(@PathVariable Integer id) {
        UserVO userVO = userService.getMemberById(id);
        return Result.success(userVO);
    }

    // 查询所有会员（支持分页）
    @GetMapping("/admin/list")
    public Result listMembers(
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String phone
    ) {
        Page<UserVO> page = userService.listMembers(pageNum, pageSize, name, phone);
        return Result.success(page);
    }

    @GetMapping("/address/{id}")
    public Result getAddress(@PathVariable Integer id){
        User user = this.userService.getBaseMapper().selectOne(Wrappers.<User>lambdaQuery().eq(User::getId, id));
        return Result.success(user);
    }

    @GetMapping("/gender")
    public Result getGenderStatistics(){
        GenderStatisticsVO genderStatisticsVO = userService.getGenderStatistics();
        return Result.success(genderStatisticsVO);
    }
}
